package com.ltmonitor.jt808.service.impl;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ltmonitor.entity.AlarmRecord;
import com.ltmonitor.entity.GPSRealData;
import com.ltmonitor.entity.VehicleData;
import com.ltmonitor.jt808.service.AlarmItem;
import com.ltmonitor.jt808.service.IAlarmService;
import com.ltmonitor.jt808.service.INewAlarmService;
import com.ltmonitor.jt808.service.INightDrivingAlarmService;
import com.ltmonitor.service.IRealDataService;
import com.ltmonitor.service.IVehicleDataService;
/**
 * 夜间行车监控，目的是禁止在夜间固定时间段
 * @author admin
 *
 */
@Service("nightDrivingAlarmService")
public class NightDrivingAlarmService implements INightDrivingAlarmService {
	@Resource
	private IRealDataService realDataService;

	@Autowired
	private IVehicleDataService vehicleDataService;
	/**
	 * 最低速度，低于此数据视为停车
	 */
	private int minSpeed = 2;
	/**
	 *只监控指定的车辆类型，如客车
	 */
	private String vehicleType;


	@Autowired
	private IAlarmService alarmService;

	@Autowired
	private INewAlarmService newAlarmService;
	

	private ConcurrentHashMap<String, AlarmItem> alarmMap = new ConcurrentHashMap<String, AlarmItem>();

	private static Logger logger = Logger.getLogger(AlarmService.class);

	/**
	 * 检测夜间行车
	 */
	public void checkNightDrivingVehicle() {
		logger.error("启动夜间行车检测服务");
		try {
			List<GPSRealData> ls = realDataService.getOnlineRealDataList();
			for (GPSRealData rd : ls) {
				String alarmKey = rd.getPlateNo() + "_"
						+ AlarmRecord.TYPE_NIGHT_DRIVING;

				if (rd.getVelocity() < minSpeed || rd.getOnline() == false) {
					if (alarmMap.containsKey(alarmKey))
					{
						this.alarmService.CreateRecord(
								AlarmRecord.ALARM_FROM_PLATFORM,
								AlarmRecord.TYPE_NIGHT_DRIVING, AlarmRecord.TURN_OFF, rd);
					}
					continue;//
				}
				VehicleData vd = vehicleDataService.load(rd.getVehicleId());
				if (vd != null && getVehicleType().equals(vd.getVehicleType())) {

					this.newAlarmService.insertAlarm(AlarmRecord.ALARM_FROM_PLATFORM,
							AlarmRecord.TYPE_NIGHT_DRIVING,  rd);
					
					if (alarmMap.containsKey(alarmKey) == false) {
						this.alarmService.CreateRecord(
								AlarmRecord.ALARM_FROM_PLATFORM,
								AlarmRecord.TYPE_NIGHT_DRIVING, AlarmRecord.TURN_ON, rd);

					}
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
	}

	


	public String getVehicleType() {
		return vehicleType;
	}

	public void setVehicleType(String vehicleType) {
		this.vehicleType = vehicleType;
	}

	public int getMinSpeed() {
		return minSpeed;
	}

	public void setMinSpeed(int minSpeed) {
		this.minSpeed = minSpeed;
	}


}
